package com.platform.common.web.controller;

import com.platform.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
@Slf4j
public class ExceptionController implements ErrorController {

    private static final String ERROR_PATH = "/error";

    @RequestMapping(value = "/error")
    public Object error(HttpServletRequest request) {
        initError(request);
        throw new BaseException("系统出错");
    }

    private void initError(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        String servletName = (String) request.getAttribute("javax.servlet.error.servlet_name");
        Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
        log.error("statusCode=" + statusCode);
        log.error("servletName=" + servletName);
        if (throwable != null) {
            log.error("message=" + throwable.getMessage());
        }

    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
}
